package cn.edu.jlu.grid.vjm;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.logging.Logger;

import org.globus.gatekeeper.GateKeeperServer;
import org.globus.gsi.GlobusCredential;
import org.globus.gsi.GlobusCredentialException;
import org.globus.gsi.gssapi.GlobusGSSCredentialImpl;
import org.globus.security.gridmap.GridMap;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;

public class VJobGateKeeperServer extends Thread {
	private GateKeeperServer gkServer = null;
	private Logger logger = Logger.getLogger(VJobGateKeeperServer.class.getName());
	
	public String getContact() {
		String s = null;
		try { s = gkServer.getContact(); } catch(Exception e){}
		return s;
	}
	public VJobGateKeeperServer() {
		
	}
	public void run() {
		/* get a valid credentials for the creating gatekeeperserver */
		String proxyFilePath = System.getenv("X509_USER_PROXY");
		GlobusCredential credentials = null;
		GSSCredential gssCredentials = null;
		
		/* for debug */
	//proxyFilePath = "/tmp/x509up_u503";
		if(proxyFilePath != null) {
			try {
				credentials = new GlobusCredential(proxyFilePath);
			} catch (GlobusCredentialException e) {
				e.printStackTrace();
			}
		} else {
			/* instruct the gram client to initiate a dynamic 
			 * delegation to get a credentials
			 */
		}
		try {
			gssCredentials = new GlobusGSSCredentialImpl(credentials,
					GSSCredential.ACCEPT_ONLY);
		} catch (GSSException e) {
			System.err.println("Failed to get credentials: " + e.getMessage());
			return;
		}
		logger.info("proxyFile: " + proxyFilePath + " credentials: " + credentials);
		
		/* set up gridmapfile for the creating gatekeeperserver */
		String localUserName = System.getenv("LOGNAME");
		GridMap gridMap = new GridMap();
		try {
		gridMap.map(gssCredentials.getName().toString(), localUserName);
		} catch (Exception e) {
			System.err.println("Failed to initialize gridmap: " + e.getMessage());
			return;
		}
		
		/* start gatekeeper server */
		gkServer = null;
		try {
			gkServer = new GateKeeperServer(gssCredentials, 0);
			gkServer.setGridMap(gridMap);
			gkServer.registerService("jobmanager", 
					"org.globus.gatekeeper.jobmanager.ForkJobManagerService",
					null);
		} catch (IOException e) {
			System.err.println("Failed to start gatekeeper: " + e.getMessage());
		} catch (ClassNotFoundException e) {
			System.err.println("Failed to start gatekeeper: " + e.getMessage());
		}
	}
}
